import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'index',
      component: () => import('../views/type_subject.vue')
    },
    {
      path: '/:type',
      name: 'type',
      component: () => import('../views/type_subject.vue')
    },
    {
      path: '/:type/:subject',
      name: 'type-subject',
      component: () => import('../views/type_subject.vue')
    },
    {
      path: '/:type/:subject/exam',
      name: 'type-subject-exam',
      component: () => import('../views/exam.vue')
    },
    {
      path: '/:type/:subject/result/:id',
      name: 'type-subject-result-id',
      component: () => import('../views/result.vue')
    },
    {
      path: '/:type/:subject/selected',
      name: 'type-subject-selected',
      component: () => import('../views/exercises.vue')
    },
    {
      path: '/:type/:subject/all',
      name: 'type-subject-all',
      component: () => import('../views/exercises.vue')
    },
    {
      path: '/:type/:subject/chapter',
      name: 'type-subject-chapter',
      component: () => import('../views/chapter.vue')
    },
    {
      path: '/:type/:subject/chapter/:chapter',
      name: 'type-subject-chapter-id',
      component: () => import('../views/exercises.vue')
    },
    {
      path: '/:type/:subject/wrong',
      name: 'type-subject-wrong',
      component: () => import('../views/exercises.vue')
    },
    {
      path: '/:type/:subject/pay',
      name: 'type-subject-pay',
      component: () => import('../views/pay.vue')
    },
    {
      path: '/login',
      component: () => import('../views/login/index.vue'),
    },
  ],
})
// 路由守卫
router.beforeEach((to, from, next) => {
  // 离开考试界面清除缓存
  if (!/^\/[a-z]+\/[0-9]+\/exam$/.test(to.path)) {
    localStorage.removeItem('examSetting')
    // 清除考试刷新标记
    if (localStorage.getItem('isRefresh')) {
      let clexid = setInterval(() => {
        if (localStorage.getItem('isRefresh')) {
          clearInterval(clexid)
          clexid = null;
        }
        localStorage.removeItem('isRefresh')
      }, 200)
    }
  }
  next()
})

export default router
